import React, { FC, useEffect, useState } from 'react';
import { FormInstance } from 'antd/lib/form';
import { Button, message } from 'antd';
import ProTable, { ProColumns } from '@/components/ProTable';
import useHoxModel from '../../../../useHoxModel';
import { AddDoorType } from '../../../../API';
import { useUnmount, useUpdateEffect } from 'ahooks';
import styles from './index.less';
// import { pick } from 'lodash';
import DoorToChoose from './DoorToChoose';
import IconFont from '@/components/IconFont';
// import { AreaListReturnProps } from '../../../../API';

const AddForm: FC<{
  formRef: React.MutableRefObject<FormInstance | undefined>;
  isEdit?: boolean;
}> = ({ formRef, isEdit }) => {
  const {
    formAreaList = [],
    getFormAreaList,
    getFormDoorList,
    formDoorList,
    dispatch,
    doorList,
  } = useHoxModel((model) => [
    model.planMode,
    model.controllerType,
    model.formAreaList,
    model.doorOpenType,
    model.formDoorList,
    model.doorList,
  ]);

  const [formAreaCode, setFormAreaCode] = useState<number>(0);

  useUnmount(() => {
    formRef.current?.resetFields();
  });
  useEffect(() => {}, []);

  useUpdateEffect(() => {
    getFormDoorList({ code: formAreaCode, number: 9999, page: 1 });
  }, [formAreaCode]);
  useUpdateEffect(() => {
    const door = formRef.current?.getFieldValue('door');
    formRef.current?.setFieldsValue({
      door: {
        ...door,
        list: formDoorList?.list || [],
      },
    });
  }, [formDoorList]);

  const loadData = async (selectedOptions: any) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;

    let res = await getFormAreaList({ id: targetOption.value });
    if (res.result === 0) {
      targetOption.loading = false;
      targetOption.children = res?.data.map((item: any) => {
        return {
          label: item.name,
          value: item.id,
          isLeaf: item.isRegion,
          code: item.code,
        };
      });
      dispatch({ formAreaList });
    }
  };

  const columns: ProColumns<AddDoorType>[] = [
    {
      title: '区域选择:',
      dataIndex: 'regionId',
      valueType: 'cascader',
      formItemProps: {
        options: formAreaList,
        loadData,
        changeOnSelect: true,
        onChange: (value: any, selectedRowKeys: any) => {
          setFormAreaCode(selectedRowKeys[selectedRowKeys.length - 1].code);
          formRef.current?.setFieldsValue({ regionId: value });
        },
      },
    },
    {
      title: '门选择:',
      dataIndex: 'door',
      renderFormItem: () => {
        return <DoorToChoose />;
      },
    },
    {
      key: 'button',
      renderFormItem: () => (
        <div className={styles['move']}>
          <Button
            onClick={() => {
              const fields = formRef.current?.getFieldsValue();
              const door = fields?.door;
              if (!door.selectedKeys || !door.selectedKeys[0]) return;
              const selectedDoorSelected = fields?.selectedDoor?.selectedKeys || [];
              const selectedDoor = fields?.selectedDoor;
              const selectedDoorIds = (selectedDoor?.list || []).map(
                (item: { id: number }) => item.id,
              );
              const existingUsers =
                door?.selectedKeys.filter((item: any) => {
                  return selectedDoorIds.includes(item.id);
                }) || [];
              const existingUsersName = existingUsers.map((app: { name: string }) => {
                return app.name;
              });
              if (existingUsersName[0]) {
                message.warn(existingUsersName.join(',') + '这些用户已经存在,没有重复的已经移入~!');
              }
              formRef.current?.setFieldsValue({
                selectedDoor: {
                  selectedKeys: selectedDoorSelected, //设置选中的数据到下面框中
                  list: (selectedDoor?.list || []).concat(
                    door?.selectedKeys.filter((item: any) => {
                      return !selectedDoorIds.includes(item.id);
                    }) || [],
                  ),
                },
                door: {
                  selectedKeys: [],
                },
              });
            }}
          >
            <IconFont type={'iconyiru'} />
            <span>移入</span>
          </Button>
        </div>
      ),
    },
    {
      title: '已选门:',
      dataIndex: 'selectedDoor',
      rules: [
        {
          required: true,
        },
      ],
      renderFormItem: () => {
        return <DoorToChoose showDeleteButton />;
      },
    },
  ];

  return (
    <div className={styles['add-form']}>
      <ProTable<AddDoorType>
        form={{
          layout: 'vertical',
          autoComplete: 'off',
          initialValues: {
            selectedDoor: {
              selectedKeys: [],
              list: doorList?.list || [],
            },
          },
        }}
        columns={columns}
        type={'form'}
        formRef={formRef}
      />
    </div>
  );
};
export default AddForm;
